﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using In.Api.Dto.HisWs;
using Common.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using User.Api.Dto.Book;
using User.Api.HttpClients;


namespace User.Api.Helpers
{
    public class CacheHelper
    {
         
        private static readonly ILog Logger = LogManager.GetLogger(typeof(CacheHelper));
        private static readonly object _lockBookObject = new object();
        private static readonly object _lockRegObject = new object();
        //预约
        private static readonly string RedisBookDoctorKey = "SdfybjyCacheBookDoctor";
        //挂号
        private static readonly string RedisRegDoctorKey = "SdfybjyCacheRegDoctor";

        public static List<DoctorSummary> GetBookDoctors()
        {
            List<DoctorSummary> departList = new List<DoctorSummary>();
            using (var muxer = ConnectionMultiplexer
                .Connect(ConfigurationManager.AppSettings["Cache_Redis_Configuration"]))
            {
                var cache = muxer.GetDatabase();
                var departStr = cache.StringGet(RedisBookDoctorKey);

                if (departStr.IsNullOrEmpty)
                {
                    lock (_lockBookObject)
                    {
                        var request = new Request4GetBookDeptList();

                        Response4GetBookDeptList response4GetBookDeptList;
                        try
                        {
                            var httpClient = InHttpClient.GetClient();
                            var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetBookDeptList", request).Result;
                            responseMsg.EnsureSuccessStatusCode();
                            response4GetBookDeptList =
                                responseMsg.Content.ReadAsAsync<Response4GetBookDeptList>().Result;
                        }
                        catch (Exception ex)
                        {
                            Logger.ErrorFormat("调用GetBookDeptList api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                            return GetBookDoctors();
                        }

                        if (response4GetBookDeptList.ResultCode != "0")
                        {
                            return GetBookDoctors();
                        }

                        foreach (var  depart in response4GetBookDeptList.BookDeptList)
                        {
                            var doctorRequest = new Request4GetBookDoctorList {DeptId = depart.DeptId};
                            try
                            {
                                var httpClient = InHttpClient.GetClient();
                                var responseMsg =
                                    httpClient.PostAsJsonAsync("HisWs/GetBookDoctorList", doctorRequest).Result;
                                responseMsg.EnsureSuccessStatusCode();
                                var response4GetBookDoctorList =
                                    responseMsg.Content.ReadAsAsync<Response4GetBookDoctorList>().Result;

                                if (response4GetBookDoctorList.ResultCode == "0")
                                {
                                    response4GetBookDoctorList.BookDoctorList.ForEach(x =>
                                    {
                                        if (!departList.Any(
                                                d => d.DoctorName == x.DoctorName && d.DeptName == depart.DeptName))
                                        {
                                            departList.Add(new DoctorSummary
                                            {
                                                DeptId = depart.DeptId,
                                                DeptName = depart.DeptName,
                                                DoctorId = x.DoctorId,
                                                DoctorName = x.DoctorName,
                                                SubjectName = x.SubjectName
                                            });
                                        }
                                    });

                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.ErrorFormat("调用GetBookDoctorList api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                            }
                        }

                        cache.StringSet(RedisBookDoctorKey, JsonConvert.SerializeObject(departList),
                            TimeSpan.FromHours(12));
                    }
                }
                else
                {
                    departList = JsonConvert.DeserializeObject<List<DoctorSummary>>(departStr);
                }
            }

            return departList;
        }

        public static List<DoctorSummary> GetRegDoctors()
        {
            List<DoctorSummary> departList = new List<DoctorSummary>();
            using (var muxer = ConnectionMultiplexer
                .Connect(ConfigurationManager.AppSettings["Cache_Redis_Configuration"]))
            {
                var cache = muxer.GetDatabase();
                var departStr = cache.StringGet(RedisRegDoctorKey);

                if (departStr.IsNullOrEmpty)
                {
                    lock (_lockRegObject)
                    {
                        var request = new Request4GetRegDeptList();
                        Response4GetRegDeptList response4GetRegDeptList;
                        try
                        {
                            var httpClient = InHttpClient.GetClient();
                            var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetRegDeptList", request).Result;
                            responseMsg.EnsureSuccessStatusCode();
                            response4GetRegDeptList = responseMsg.Content.ReadAsAsync<Response4GetRegDeptList>().Result;
                        }
                        catch (Exception ex)
                        {
                            Logger.ErrorFormat("调用院内GetRegDeptList api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                            return GetRegDoctors();
                        }

                        if (response4GetRegDeptList.ResultCode != "0")
                        {
                            return GetRegDoctors();
                        }

                        foreach (var depart in response4GetRegDeptList.RegDeptList)
                        {

                            var doctorRequest = new Request4GetRegDoctorList {DeptId = depart.DeptId};

                            try
                            {
                                var httpClient = InHttpClient.GetClient();
                                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetRegDoctorList", doctorRequest).Result;
                                responseMsg.EnsureSuccessStatusCode();
                                var response4GetRegDoctorList = responseMsg.Content.ReadAsAsync<Response4GetRegDoctorList>().Result;

                                if (response4GetRegDoctorList.ResultCode == "0")
                                {
                                    response4GetRegDoctorList.RegDoctorList.ForEach(x =>
                                    {
                                        if (x.State.ToLower() == "开诊")
                                        {
                                            if (!departList.Any(
                                                d => d.DoctorName == x.DoctorName && d.DeptName == depart.DeptName))
                                            {
                                                departList.Add(new DoctorSummary
                                                {
                                                    DeptId = depart.DeptId,
                                                    DeptName = depart.DeptName,
                                                    DoctorId = x.DoctorId,
                                                    DoctorName = x.DoctorName
                                                });
                                            }
                                        }
                                    });
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.ErrorFormat("调用院内GetRegDoctorList Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                            }

                        }

                        cache.StringSet(RedisRegDoctorKey, JsonConvert.SerializeObject(departList),
                            TimeSpan.FromHours(12));
                    }
                }
                else
                {
                    departList = JsonConvert.DeserializeObject<List<DoctorSummary>>(departStr);
                }
            }

            return departList;
        }
    }
}